<?php

namespace App\Repositories;

use Exception;
use App\Models\Demand;
use App\Models\Schedule;
use Illuminate\Support\Facades\Auth;
use App\Exceptions\GeneralException;
use App\Package\Attendance\ScheduleGenerator;
use Illuminate\Support\Facades\DB;

/**
 * 排班逻辑
 *
 * Date: 25/04/2018
 * @author George
 * @package App\Repositories
 */
class ScheduleRepository
{
	/**
	 * 验证数据是否存在
	 *
	 * Date: 25/04/2018
	 * @author George
	 * @param $project_id
	 * @param $demand_id
	 * @param $users_id
	 * @return integer
	 */
	public function verification($project_id, $demand_id, array $users_id)
	{
		return Schedule::query()->where([
			['project_id', '=', $project_id],
			['demand_id', '=', $demand_id]
		])->whereIn('user_id', $users_id)->count();
	}

	/**
	 * 创建排班记录
	 *
	 * Date: 02/05/2018
	 * @author George
	 * @param array $attributes
	 * @return array
	 * @throws GeneralException
	 */
	public function store(array $attributes)
	{
		$demand = Demand::with('genre')->where('id', $attributes['demand_id'])->first();
		if (! $demand) {
			throw new GeneralException('提供的项目需求信息不存在', 422);
		}

		$schedules = [];
		$users_id = array_pull($attributes, 'users_id');
		$generator = new ScheduleGenerator();

		try {
			DB::beginTransaction();
			foreach ($users_id as $user_id) {
				$attributes['user_id'] = $user_id;
				$attributes['genre_id'] = $demand->genre_id;
				$attributes['genre_name'] = $demand->genre->name;
				$attributes['date'] = $demand->date;
				$attributes['start'] = $demand->genre->start;
				$attributes['end'] = $demand->genre->end;
				$attributes['start_timestamp'] = $attributes['date'] . ' ' . $attributes['start'];
				$attributes['end_timestamp'] = $generator->endTime($attributes['start'], $attributes['end'], $attributes['date']);// 计算工作时长
				$attributes['worktime'] = strtotime($attributes['end_timestamp']) - strtotime($attributes['start_timestamp']);// 判断是否跨天
				$attributes['span'] = $attributes['start'] > $attributes['end'];
				$attributes['company_id'] = Auth::user()->company_id;
				$schedules[] = Schedule::create($attributes);
			}
			DB::commit();
		} catch (Exception $exception) {
			DB::rollBack();
			throw new GeneralException('保存排班数据失败', 500);
		}

		return $schedules;
	}
}
